package com.wx.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.simpleimage.ImageRender;
import com.alibaba.simpleimage.SimpleImageException;
import com.alibaba.simpleimage.render.CropParameter;
import com.alibaba.simpleimage.render.CropRender;
import com.alibaba.simpleimage.render.ReadRender;
import com.alibaba.simpleimage.render.ScaleParameter;
import com.alibaba.simpleimage.render.ScaleRender;
import com.alibaba.simpleimage.render.WriteRender;

public class ImageUtilByAli {

	private static Logger logger = LoggerFactory.getLogger(ImageUtilByAli.class);
	
	public static void main(String[] args) throws Exception {
		//crop("D:\\LOG\\94381436167112194.jpg", "D:\\aaa12233330.5.jpg", 100, 100,100, 100);
		scale("D:\\LOG\\d130ee2d2fa98f352b9b67f4b54f6cf4.jpg", "D:\\LOG\\d130ee2d2fa98f352b9b67f4b54f6cf4.2.128x128.jpg", Integer.MAX_VALUE, 128);
	}

	/**
	 * 转发网络图片流形式输出
	 * @param url
	 * @throws IOException
	 */
	public static boolean cteateImgByNet(String urlnet,String tmpPath){
        try {
			URL url = new URL(urlnet);   // 构造URL  
			URLConnection con = url.openConnection();     // 打开连接  
			con.setConnectTimeout(5*1000);    //设置请求的路径  
			InputStream imageIn = con.getInputStream(); // 输入流  
			//得到图片的二进制数据，以二进制封装得到数据，具有通用性  
			byte[] data = readInputStream(imageIn);  
			//new一个文件对象用来保存图片，默认保存当前工程根目录  
			File imageFile = new File(tmpPath);
			//创建输出流  
			FileOutputStream outStream = new FileOutputStream(imageFile);  
			//写入数据  
			outStream.write(data);  
			//关闭输出流  
			outStream.close();
		} catch (Exception e) {
			e.printStackTrace();
			 return false;
		} 
        return true;
	}
	
	private static byte[] readInputStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        //创建一个Buffer字符串  
        byte[] buffer = new byte[4096];  
        //每次读取的字符串长度，如果为-1，代表全部读取完毕  
        int len = 0;  
        //使用一个输入流从buffer里把数据读取出来  
        while( (len=inStream.read(buffer)) != -1 ){  
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
            outStream.write(buffer, 0, len);  
        }  
        //关闭输入流  
        inStream.close();  
        //把outStream里的数据写入内存  
        return outStream.toByteArray();  
    } 
	
	/**
	 * 剪切图片
	 * 
	 * @param inPath 原图
	 * @param outPath 新图
	 * @param x 
	 * @param y
	 * @param width
	 * @param height
	 */
	public static boolean crop(String inPath, String outPath, int x, int y,
			int width, int height) {
		System.setProperty("java.awt.headless", "true");
		File in = new File(inPath); // 原图片
		File out = new File(outPath); // 目的图片
		FileInputStream inStream = null;
		FileOutputStream outStream = null;
		WriteRender wr = null;
		boolean flag= false;
		try {
			inStream = new FileInputStream(in);
			outStream = new FileOutputStream(out);
			ImageRender rr = new ReadRender(inStream);
			CropParameter param = new CropParameter(x, y, width, height);
			ImageRender sr = new CropRender(rr, param);
			wr = new WriteRender(sr, outStream);
			logger.debug("--下面的代码在某些linux下不执行");
			wr.render(); //触发图像处理
			flag=true;
		} catch (SimpleImageException e) {
			logger.debug(e.toString());
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			logger.debug(e.toString());
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(inStream); // 图片文件输入输出流必须记得关闭
			IOUtils.closeQuietly(outStream);
			if (wr != null) {
				try {
					wr.dispose(); // 释放simpleImage的内部资源
				} catch (SimpleImageException ignore) {
				}
			}
		}
		 return flag;
	}

	/**
	 * 压缩图片
	 * @param inPath 原图
	 * @param outPath 新图
	 * @param maxWidth 
	 * @param maxHeight
	 */
	public static boolean scale(String inPath, String outPath, int maxWidth,
			int maxHeight) {
		File in = new File(inPath); // 原图片
		File out = new File(outPath); // 目的图片
		FileInputStream inStream = null;
		FileOutputStream outStream = null;
		WriteRender wr = null;
		boolean flag= false;
		try {
			inStream = new FileInputStream(in);
			outStream = new FileOutputStream(out);
			ImageRender rr = new ReadRender(inStream);
			ScaleParameter scaleParam = new ScaleParameter(maxWidth, maxHeight);
			ImageRender sr = new ScaleRender(rr, scaleParam);
			wr = new WriteRender(sr, outStream);
			wr.render(); // 触发图像处理
			flag=true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(inStream); // 图片文件输入输出流必须记得关闭
			IOUtils.closeQuietly(outStream);
			if (wr != null) {
				try {
					wr.dispose(); // 释放simpleImage的内部资源
				} catch (SimpleImageException ignore) {
				}
			}
		}
		 return flag;
	}
	
}
